package com.qing.design.patterns.memento.example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 管理员类
 */
public class Admin {

	private int cursorIdx=-1; //初始化为-1保证如果有数据，下标从0开始

	private List<ConfigMemento> mementoList=new ArrayList<>();

	private Map<String,ConfigMemento> mementoMap=new ConcurrentHashMap<>();


	public void append(ConfigMemento memento){
		mementoList.add(memento);
		mementoMap.put(memento.getConfigFile().getVersionNo(),memento);
		cursorIdx++;
	}

	//获取上一个版本
	public ConfigMemento undo(){
		if(--cursorIdx<=0) return mementoList.get(0);
		return mementoList.get(cursorIdx);
	}

	//前进
	public ConfigMemento redo(){
		//TODO 边界处理，算法十分高效
		if(++cursorIdx>mementoList.size()) return mementoList.get(mementoList.size()-1);
		return mementoList.get(cursorIdx);
	}



	public ConfigMemento get(String versionNo){
		return  mementoMap.get(versionNo);
	}
}
